package interview.dp;

/**
 * @author fance
 * @date 2018/6/10 17:17
 */
public class Solution {
    // 压缩空间 最小路径和
    public int minPathSum(int[][] m) {
        if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
            return 0;
        }
        int more = Math.max(m.length,m[0].length);
        int less = Math.min(m.length,m[0].length);
        boolean rowMore = more == m.length;
        int[] dp = new int[less];
        dp[0] = m[0][0];
        for (int i = 1; i < less; i++) {
            dp[i] = dp[i - 1] + (rowMore ? m[0][i] : m[i][0]);
        }

        for (int i = 1; i < more; i++) {
            dp[0] = dp[0] + (rowMore ? m[i][0] : m[0][i]);
            for (int j = 1; j < less; j++) {
                dp[j] = Math.min(dp[j - 1],dp[j]) +
                        (rowMore ? m[i][j] : m[j][i]);
            }
        }
        return dp[less - 1];
    }
}
